<?php

/**
 * Created by PhpStorm.
 * User: dumbledore
 * Date: 2018/3/23
 * Time: 下午1:50
 */
class Cost_center extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->database();
        $this->load->library('form_validation'); //加载表单验证类库
        $this->load->helper('json');
        $this->load->helper('url');
        $this->load->helper('common');
        $this->load->model('user_model');
        $this->load->model('customer_model');
        $this->load->model('goods_model');
        $this->load->model('member_model');
        $this->load->model('admin_model');
        $this->load->model('cost_center_model');
        $this->load->model('api_model');
        $this->load->library('session');
        $this->load->library('message');
    }

    // 成本中心列表
    public function cost_center_list()
    {
        if ($this->session->customer_id) {
            $post        = $this->input->post();
            $name        = isset($post['name']) ? $post['name'] : '';
            $customer_id = $this->session->customer_id;
            $identity    = $this->session->customer_info['identity'];
            $res         = $this->cost_center_model->query_cost_center_list($customer_id, $name);
            send_json(array('code' => 0, 'data' => $res, 'identity' => $identity, 'msg' => "success"));
        } else {
            send_json(array('code' => 0, 'data' => array(), 'identity' => 0, 'msg' => "success"));
        }
    }

    // 管理账号 列表
    public function query_manager_list()
    {
        $customer_id    = $this->session->customer_id;
        $customer_info  = $this->session->customer_info;
        $post           = $this->input->post();
        $cost_center_id = isset($post['cost_center_id']) ? $post['cost_center_id'] : '';

        //获取登錄用戶下面的子辈或孙辈的(包含自己)
        $all_id = $this->customer_model->get_customer_user($customer_id);

        $data[1] = $this->db->where(array('cost_center_id' => $cost_center_id, 'identity' => 2))->where_in('id', $all_id)->order_by('id', 'desc')->from('app_customer')->get()->result_array();
        $data[2] = $this->db->where(array('cost_center_id' => $cost_center_id, 'identity' => 3))->where_in('id', $all_id)->order_by('id', 'desc')->from('app_customer')->get()->result_array();

        // $username = isset($post['username']) ? $post['username'] : '';
        // $cost_center_id = isset($post['cost_center_id']) ? $post['cost_center_id'] : '';
        // if ($customer_info['identity'] == 1) {
        //     $res = $this->cost_center_model->query_manager_list($customer_id, $cost_center_id, $username);
        //     $parent_id = $this->customer_model->get_customer_user_parent($customer_id);
        //     $user = $this->db->from('app_customer')->where_in('id', $parent_id['str2'])->get()->result_array();
        // }
        // if ($customer_info['identity'] == 2) {
        //     $sql = "SELECT username,id FROM app_customer WHERE identity = 2 AND  cost_center_id=" . $cost_center_id . " AND  id = " . $customer_id;
        //     $res = $this->db->query($sql)->row_array();
        //     $sql2 = "select * from app_customer WHERE identity = 3 AND   parent_id = " . $customer_id;
        //     $user = $this->db->query($sql2)->result_array();
        // }
        // $data[2] = $user;
        // $data[1] = $res;
        $identity = $customer_info['identity'];
        send_json(array('code' => 0, 'data' => $data, 'identity' => $identity, 'msg' => "success"));
    }

    // 用户账号 列表
    public function query_user_list()
    {
        $post           = $this->input->post();
        $cost_center_id = isset($post['cost_center_id']) ? $post['cost_center_id'] : '';

        $username       = isset($post['username']) ? $post['username'] : '';
        $parent_id      = isset($post['parent_id']) ? $post['parent_id'] : '';
        $cost_center_id = isset($post['cost_center_id']) ? $post['cost_center_id'] : '';
        if (!$parent_id) {
            send_json(array('code' => -1, 'data' => '', 'msg' => "缺少参数"));
        }
        $res = $this->cost_center_model->query_user_list($parent_id, $username);
        send_json(array('code' => 0, 'data' => $res, 'msg' => "success"));
    }

    // 成本中心 首页
    public function cost_center_index()
    {
        $customer_info    = $this->session->customer_info;
        $customer_id      = $this->session->customer_id;
        $cost_center_name = isset($_GET['cost_center']) ? $_GET['cost_center'] : '';
        $manager          = isset($_GET['manager']) ? $_GET['manager'] : '';
        $user             = isset($_GET['user']) ? $_GET['user'] : '';
        $manager_list     = array();
        $row              = array();

        if ($customer_info['identity'] == 3) {
            redirect('cost_center/no_permission_index');
        }
        if ($customer_id) {

            if ($customer_info['identity'] == 1) {
                $all_id         = $this->customer_model->get_customer_user($customer_id);
                $manager_list   = $this->db->where(array('identity' => 2))->where_in('id', $all_id)->order_by('id', 'desc')->from('app_customer')->get()->result_array();
                $row            = $this->db->where(array('identity' => 3))->where_in('id', $all_id)->from('app_customer')->get()->result_array();
                $cost_center    = $this->db->where(array('customer_id' => $customer_id))->order_by('id', 'desc')->from('app_cost_center')->get()->result_array();
                $cost_center_id = array('0' => '-1');
                $manager_id     = array();
                if ($cost_center_name) {
                    $cost_center = $this->db->where(array('customer_id' => $customer_id))->like('name', $cost_center_name)->order_by('id', 'desc')->from('app_cost_center')->get()->result_array();

                    foreach ($cost_center as $key => $cost) {
                        $cost_center_id[] = $cost['id'];
                    }

                    $manager_list = $this->db->where(array('identity' => 2))->where_in('cost_center_id', $cost_center_id)->where_in('id', $all_id)->order_by('id', 'desc')->from('app_customer')->get()->result_array();
                    $row          = $this->db->where(array('identity' => 3))->where_in('cost_center_id', $cost_center_id)->where_in('id', $all_id)->order_by('id', 'desc')->from('app_customer')->get()->result_array();
                }
                if ($manager) {
                    $manager_list = $this->db->where(array('identity' => 2))->like('username', $manager)->where_in('id', $all_id)->from('app_customer')->order_by('id', 'desc');
                    if ($cost_center_id) {
                        $manager_list = $manager_list->where_in('cost_center_id', $cost_center_id);
                    }
                    $manager_list = $manager_list->get()->result_array();
                    foreach ($manager_list as $key => $man) {
                        $center_id[]  = $man['cost_center_id'];
                        $manager_id[] = $man['id'];
                    }
                    $row = $this->db->where(array('identity' => 3))->from('app_customer')->order_by('id', 'desc');
                    if ($manager_id) {
                        $row = $row->where_in('parent_id', $manager_id);
                    }
                    if ($cost_center_id) {
                        $row = $row->where_in('cost_center_id', $cost_center_id);
                    }
                    $row = $row->get()->result_array();
                }
                if ($user) {
                    $row = $this->db->where(array('identity' => 3))->like('username', $user)->where_in('id', $all_id)->from('app_customer')->order_by('id', 'desc');
                    if ($cost_center_id) {
                        $row = $row->where_in('cost_center_id', $cost_center_id);
                    }
                    if ($manager_id) {
                        $row = $row->where_in('parent_id', $manager_id);
                    }
                    $row = $row->get()->result_array();
                }
                //print_r($row);
            };
            if ($customer_info['identity'] == 2) {
                $manager_info = $this->db->select('cost_center_id')->where(array('id' => $customer_id))->from('app_customer')->get()->row_array();
                $cost_center  = $this->db->where(array('id' => $manager_info['cost_center_id']))->from('app_cost_center')->get()->result_array();
                $all_id       = $this->customer_model->get_customer_user($customer_id);
                $manager_list = $this->db->where(array('cost_center_id' => $manager_info['cost_center_id'], 'identity' => 2))->where_in('id', $all_id)->order_by('id', 'desc')->from('app_customer')->get()->result_array();
                $row          = $this->db->where(array('cost_center_id' => $manager_info['cost_center_id'], 'identity' => 3))->where_in('id', $all_id)->order_by('id', 'desc')->from('app_customer')->get()->result_array();
                if ($user) {
                    $row = $this->db->where(array('identity' => 3))->like('username', $user)->where_in('id', $all_id)->from('app_customer')->order_by('id', 'desc');
                    $row = $row->get()->result_array();
                }
            };
            $data['cost_center'] = $cost_center;
            $data['user']        = $row;
            $data['manage']      = $manager_list;
        }
        $data['customer_info'] = $customer_info;
        $this->load->view('cost_center/cost_center_index.php', $data);
    }

    // 创建成本中心
    public function create_cost_center_index()
    {
        $customer_info = $this->session->customer_info;
        $customer_id   = $this->session->customer_id;
        if ($customer_info['identity'] != 1) {
            redirect('cost_center/no_permission_index');
        }
        $where                 = array('id' => $customer_id);
        $data['company']       = $this->db->where($where)->from('app_customer')->get()->row_array()['company'];
        $data['customer_info'] = $customer_info;
        $this->load->view('cost_center/create_cost_center_index.php', $data);

    }

    // 保存成本中心
    public function save_cost_center_index()
    {
        $customer_info = $this->session->customer_info;
        $customer_id   = $this->session->customer_id;

        $post = $this->input->post();
        if (check_param($post, ['name'])) {
            if ($customer_info['identity'] != 1) {
                send_json(array('code' => -1, 'data' => '', 'msg' => "需要admin权限"));
            }
            $re = check_uniqueness($this->db, 'app_cost_center', 'name', $post['name']);
            if (!$re) {
                send_json(array('code' => -1, 'data' => '', 'msg' => "部门名重复"));
            }
            $res = $this->cost_center_model->add_cost_center($customer_id, $post['name']);
            if ($res) {
                send_json(array('code' => 0, 'data' => '', 'msg' => "保存成功"));
            } else {
                send_json(array('code' => -1, 'data' => '', 'msg' => "保存失败"));
            }
        } else {
            send_json(array('code' => -1, 'data' => '', 'msg' => "缺少参数"));
        }
    }

    // 修改成本中心
    public function update_cost_center_index()
    {
        $customer_id = $this->session->customer_id;
        if ($_GET['cost_center_id']) {
            $cost_center_id     = $_GET['cost_center_id'];
            $row                = $this->db->from('app_cost_center')->select('name,id')->where('id', $cost_center_id)->get()->row_array();
            $row['cost_center'] = $row;
            $this->load->view('cost_center/update_cost_center_index.php', $row);
        } else {
            exit('没有此成本中心');
        }
    }

    // 修改成本中心
    public function edit_cost_center_index()
    {
        $customer_info = $this->session->customer_info;
        $customer_id   = $this->session->customer_id;

        $post = $this->input->post();
        if (check_param($post, ['name'])) {
            if ($customer_info['identity'] != 1) {
                send_json(array('code' => -1, 'data' => '', 'msg' => "需要admin权限"));
            }
            $re = check_uniqueness($this->db, 'app_cost_center', 'name', $post['name']);
            if (!$re) {
                send_json(array('code' => -1, 'data' => '', 'msg' => "部门名重复"));
            }
            $res = $this->cost_center_model->edit_cost_center($customer_id, $post['name'], $post['id']);
            if ($res) {
                send_json(array('code' => 0, 'data' => '', 'msg' => "修改成功"));
            } else {
                send_json(array('code' => -1, 'data' => '', 'msg' => "修改失败"));
            }
        } else {
            send_json(array('code' => -1, 'data' => '', 'msg' => "缺少参数"));
        }
    }

    //冻结账户
    public function freeze_account()
    {
        $post = $this->input->post();
        $res  = $this->db->where(array("id" => $post['id']))->update('app_customer', ['status' => 0]);
        if ($res) {
            send_json(array('code' => 0, 'data' => "", 'msg' => "已冻结"));
        } else {
            send_json(array('code' => -1, 'data' => "", 'msg' => "冻结失败"));
        }
    }

    //解冻账户
    public function unfreeze_account()
    {
        $post = $this->input->post();
        $res  = $this->db->where(array("id" => $post['id']))->update('app_customer', ['status' => 1]);
        if ($res) {
            send_json(array('code' => 0, 'data' => "", 'msg' => "已解冻"));
        } else {
            send_json(array('code' => -1, 'data' => "", 'msg' => "冻结失败"));
        }
    }

    //设为默认抬头
    public function default_look_up()
    {
        $post  = $this->input->post();
        $bool1 = $this->db->where(array("customer_id" => $post['user_id']))->update('app_invoice', ['is_default' => 0]);
        $bool2 = $this->db->where(array("customer_id" => $post['user_id'], "id" => $post['id']))->update('app_invoice', ['is_default' => 1]);
        if ($bool1 && $bool2) {
            send_json(array('code' => 0, 'data' => "", 'msg' => "设置成功"));
        } else {
            send_json(array('code' => -1, 'data' => "", 'msg' => "设置失败"));
        }
    }

    //设为默认地址
    public function default_address()
    {
        $post = $this->input->post();

        $res1 = $this->user_model->change_user_default_address_byid($post['user_id'], $post['id']);
        //获取商城用户id
        $data['shop_user_id'] = $this->user_model->customer_id_to_shop_user_id($post['user_id']);
        //获取商城地址id
        $where           = array('id' => $post['id']);
        $data['shop_id'] = $this->db->where($where)->from('app_address')->get()->row_array()['shop_id'];
        //同步默认地址
        $res2 = $this->member_model->company_user_address_default($data);

        if ($res1 && $res2) {
            send_json(array('code' => 0, 'data' => "", 'msg' => "设置成功"));
        } else {
            send_json(array('code' => -1, 'data' => "", 'msg' => "设置失败"));
        }
    }

    /*
     * 添加/修改发票信息
     * $post['id'] 为发票id ，$post['type'] 发票类型 $post['uid'] 发票用户customer_id
     */
    public function add_mdy_invoice()
    {
        $customer_id  = $this->session->customer_id;
        $shop_user_id = $this->user_model->customer_id_to_shop_user_id($customer_id);
        $post         = $this->input->post();
        if ($post) {
            //普通发票的增加或者修改和同步
            if ($post['type'] == 4) {
                $data['customer_id']          = isset($post['uid']) ? $post['uid'] : "";
                $data['invoice_type']         = isset($post['type']) ? $post['type'] : "";
                $data['invoice_company_name'] = isset($post['title']) ? $post['title'] : "";
                $data['invoice_content']      = isset($post['cont']) ? $post['cont'] : 1;
                $data['invoice_code']         = isset($post['qycode']) ? $post['qycode'] : "";
                $data['is_default']           = isset($post['is_default']) ? $post['is_default'] : 1;
                if ($data['is_default'] == 1) {
                    $where = array('customer_id' => $post['uid']);
                    $this->db->where($where)->update('app_invoice', array('is_default' => 0));
                }
                if ($post['invoice_id'] == 0) {
                    $res        = $this->db->insert('app_invoice', $data);
                    $invoice_id = $this->db->insert_id();
                    if ($res) {
                        $data['shop_user_id'] = $shop_user_id;
                        $shop_id              = $this->member_model->company_user_invoice($data);
                        $where                = array('id' => $invoice_id);
                        $this->db->where($where)->update('app_invoice', array('shop_id' => $shop_id['data']));
                        $invoice_list = $this->db->query("select * from app_invoice WHERE customer_id = " . $data['customer_id'])->result_array();
                        send_json(array('code' => 0, 'data' => array('invoice_list' => $invoice_list), 'msg' => "保存成功"));
                    } else {
                        send_json(array('code' => -1, 'data' => "", 'msg' => '添加失败'));
                    }
                } else {
                    $where = array('id' => $post['invoice_id']);
                    $res   = $this->db->where($where)->update('app_invoice', $data);
                    if ($res) {
                        $row                  = $this->db->select('shop_id')->where($where)->from('app_invoice')->get()->row_array();
                        $data['shop_id']      = $row['shop_id'];
                        $data['shop_user_id'] = $shop_user_id;
                        $this->member_model->company_user_invoice($data);
                        $invoice_list = $this->db->query("select * from app_invoice WHERE customer_id = " . $data['customer_id'])->result_array();
                        send_json(array('code' => 0, 'data' => array('invoice_list' => $invoice_list), 'msg' => "保存成功"));
                    } else {
                        send_json(array('code' => -1, 'data' => "", 'msg' => '修改失败'));
                    }
                }
                //增值发票的增加或者修改和同步
            } elseif ($post['type'] == 2) {
                $data['customer_id']          = isset($post['uid']) ? $post['uid'] : "";
                $data['invoice_type']         = isset($post['type']) ? $post['type'] : "";
                $data['invoice_company_name'] = isset($post['company']) ? $post['company'] : "";
                $data['invoice_address']      = isset($post['address']) ? $post['address'] : "";
                $data['invoice_tel']          = isset($post['tel']) ? $post['tel'] : "";
                $data['invoice_bank']         = isset($post['bank']) ? $post['bank'] : "";
                $data['invoice_account']      = isset($post['card']) ? $post['card'] : "";
                $data['invoice_code']         = isset($post['texpayer']) ? $post['texpayer'] : "";
                $data['is_default']           = isset($post['is_default']) ? $post['is_default'] : 1;
                if ($data['is_default'] == 1) {
                    $where = array('customer_id' => $post['uid']);
                    $this->db->where($where)->update('app_invoice', array('is_default' => 0));
                }
                if ($post['invoice_id'] == 0) {
                    $res        = $this->db->insert('app_invoice', $data);
                    $invoice_id = $this->db->insert_id();
                    if ($res) {
                        $data['shop_user_id'] = $shop_user_id;
                        $shop_id              = $this->member_model->company_user_invoice($data);
                        $where                = array('id' => $invoice_id);
                        $this->db->where($where)->update('app_invoice', array('shop_id' => $shop_id['data']));
                        $invoice_list = $this->db->query("select * from app_invoice WHERE customer_id = " . $data['customer_id'])->result_array();
                        send_json(array('code' => 0, 'data' => array('invoice_list' => $invoice_list), 'msg' => "保存成功"));
                    } else {
                        send_json(array('code' => -1, 'data' => "", 'msg' => '添加失败'));
                    }
                } else {
                    $where = array('id' => $post['invoice_id']);
                    $res   = $this->db->where($where)->update('app_invoice', $data);
                    if ($res) {
                        $row                  = $this->db->select('shop_id')->where($where)->from('app_invoice')->get()->row_array();
                        $data['shop_id']      = $row['shop_id'];
                        $data['shop_user_id'] = $shop_user_id;
                        $this->member_model->company_user_invoice($data);
                        $invoice_list = $this->db->query("select * from app_invoice WHERE customer_id = " . $data['customer_id'])->result_array();
                        send_json(array('code' => 0, 'data' => array('invoice_list' => $invoice_list), 'msg' => "保存成功"));
                    } else {
                        send_json(array('code' => -1, 'data' => "", 'msg' => '修改失败'));
                    }
                }

            } else {
                send_json(array('code' => 0, 'data' => "", 'msg' => '暂不需要'));
            }
        }

    }

    //修改地址
    public function add_address()
    {
        $post = $this->input->post();
        if (check_param($post, ['name', 'province', 'city', 'district', 'address', 'phone'])) {
            $data['customer_id'] = isset($post['user_id']) ? $post['user_id'] : "";
            $data['name']        = isset($post['name']) ? $post['name'] : "";
            $data['province']    = isset($post['province']) ? $post['province'] : "";
            $data['city']        = isset($post['city']) ? $post['city'] : "";
            $data['district']    = isset($post['district']) ? $post['district'] : "";
            $data['postcode']    = isset($post['postcode']) ? $post['postcode'] : "";
            $data['address']     = isset($post['address']) ? $post['address'] : "";
            $data['phone']       = isset($post['phone']) ? $post['phone'] : "";
            $data['tel']         = isset($post['tel']) ? $post['tel'] : "";
            $data['region_id']   = isset($post['regionId']) ? $post['regionId'] : "";
            $data['is_default']  = isset($post['is_default']) ? $post['is_default'] : "";

            // 更新
            if (isset($post['address_id']) && $post['address_id']) {
                $this->db->where(array("id" => $post['address_id']))->update('app_address', $data);
                //获取商城shop_user_id
                $data['shop_user_id'] = $this->user_model->customer_id_to_shop_user_id($data['customer_id']);
                //获取商城地址shop_id
                $adderss         = $this->db->select('shop_id,id')->where(array("id" => $post['address_id']))->from('app_address')->get()->row_array();
                $data['shop_id'] = $adderss['shop_id'];

                //同步修改地址

                $data['region_name'] = $post['province'] . $post['city'] . $post['district'];
                $this->member_model->company_user_address($data);
                // 设置默认地址
                if (isset($post['is_default']) && $post['is_default'] == 1) {
                    $this->user_model->change_user_default_address_byid($data['customer_id'], $adderss['id']);
                    //同步默认地址
                    $this->member_model->company_user_address_default($data);
                }
                $address_list = $this->db->query("select * from app_address WHERE customer_id = " . $data['customer_id'])->result_array();

                send_json(array('code' => 0, 'data' => array('address_list' => $address_list), 'msg' => "保存成功"));
            }
            // 新增
            $where   = array('customer_id' => $data['customer_id'], 'is_default' => 1);
            $adderss = $this->db->where($where)->get('app_address')->row_array();
            if ($adderss) {
                $data['is_default'] = 0;
            } else {
                $data['is_default'] = 1;
            }
            $res = $this->db->insert('app_address', $data);
            if ($res) {
                $data['id'] = $this->db->insert_id();
                //获取商城shop_user_id
                $data['shop_user_id'] = $this->user_model->customer_id_to_shop_user_id($data['customer_id']);
                //同步新增地址
                $data['region_name'] = $post['province'] . $post['city'] . $post['district'];
                $rrr                 = $this->member_model->company_user_address($data);
                $data['shop_id']     = $rrr;
                if ($data['is_default'] == 1) {
                    $this->member_model->company_user_address_default($data);
                }
                $this->db->where(array("id" => $data['id']))->update('app_address', array('shop_id' => $rrr));
            }

            if ($data['id']) {

                // 设置默认地址
                if (isset($post['is_default']) && $post['is_default'] == 1) {
                    $this->user_model->change_user_default_address_byid($data['customer_id'], $data['id']);
                    //同步默认地址
                    $this->member_model->company_user_address_default($data);

                }
                $address_list = $this->db->query("select * from app_address WHERE customer_id = " . $data['customer_id'])->result_array();
                send_json(array('code' => 0, 'data' => array('address_list' => $address_list), 'msg' => "保存成功"));

            } else {
                send_json(array('code' => 1, 'data' => '', 'msg' => '添加失败'));
            }

        } else {
            send_json(array('code' => -1, 'data' => '', 'msg' => "缺少参数"));
        }
    }

    public function address_info()
    {
        $post = $this->input->post();
        if (check_param($post, ['id'])) {
            $sql  = "select * from app_address WHERE id = " . $post['id'];
            $data = $this->db->query($sql)->row_array();
            send_json(array('code' => 0, 'data' => $data, 'msg' => "success"));
        } else {
            send_json(array('code' => -1, 'data' => '', 'msg' => "缺少参数"));
        }

    }

    //发票信息
    public function invoice_info()
    {
        $post = $this->input->post();
        if (check_param($post, ['id'])) {
            $sql  = "select * from app_invoice WHERE id = " . $post['id'];
            $data = $this->db->query($sql)->row_array();
            send_json(array('code' => 0, 'data' => $data, 'msg' => "success"));
        } else {
            send_json(array('code' => -1, 'data' => '', 'msg' => "缺少参数"));
        }

    }

    // 修改admin 前缀
    public function change_prefix()
    {
        $customer_info = $this->session->customer_info;
        $customer_id   = $this->session->customer_id;
        $post          = $this->input->post();
        if ($post['prefix'] == "") {
            send_json(array('code' => -1, 'data' => '', 'msg' => "前缀不可为空"));
        }
        if ($customer_info['identity'] != 1) {
            send_json(array('code' => -1, 'data' => '', 'msg' => "需要admin权限"));
        }
        if (check_param($post, ['prefix'])) {
            $res = $this->admin_model->change_prefix($customer_id, $post['prefix']);
            send_json($res);
        } else {
            send_json(array('code' => -1, 'data' => '', 'msg' => "缺少参数"));
        }

    }

    // 保存管理/用户账号信息
    public function save_manager_user()
    {
        $customer_id = $this->session->customer_id;
        //获取admin的信息
        $admin_info_id = $this->customer_model->get_admin_customer_id($customer_id);
        $admin_info    = $this->db->where(array('customer_id' => $admin_info_id))->from('app_admin')->get()->row_array();
        $post          = $this->input->post();
        if (check_param($post, ['cost_center_id', 'username', 'password', 'name', 'tel', 'email', 'u_prefix', 'parent_id'])) {
            $this->db->trans_begin();
            //获取用户的信息
            $customer_info = $this->customer_model->query_customer_info($customer_id);
            // 基本信息 保存app_customer
            $d1['cost_center_id'] = $post['cost_center_id'];
            $d1['username']       = $post['u_prefix'] . $post['username'];
            $d1['password']       = $post['password'];
            $d1['manager_id']     = $customer_info['manager_id'];
            $d1['company']        = $customer_info['company'];
            $d1['name']           = $post['name'];
            $d1['tel']            = $post['tel'];
            $d1['status']         = 1;
            $d1['email']          = $post['email'];
            $where                = array('username' => $d1['username']);
            $res                  = $this->db->where($where)->from('app_customer')->get()->row_array();
            if ($res) {
                send_json(array('code' => -1, 'data' => '', 'msg' => "该账号已被注册"));
            }
            $where = array('tel' => $d1['tel']);
            $res   = $this->db->where($where)->from('app_customer')->get()->row_array();
            if ($res) {
                send_json(array('code' => -1, 'data' => '', 'msg' => "该手机号已被注册"));
            }
            $where = array('email' => $d1['email']);
            $res   = $this->db->where($where)->from('app_customer')->get()->row_array();
            if ($res) {
                send_json(array('code' => -1, 'data' => '', 'msg' => "该电子邮箱地址已存在"));
            }

            //获取上级id身份
            $admin_id = $this->user_model->customer_id_to_identity($post['parent_id']);

            if ($admin_id == 2) {
                //获取上级用户信息
                $parent_info = $this->db->where(array('customer_id' => $post['parent_id']))->from('app_manager_user')->get()->row_array();
                if ($parent_info['total_quota'] != 0) {
                    if (!$post['total_quota']) {
                        send_json(array('code' => -1, 'data' => '', 'msg' => "由于上级账号每月额度有限制，所以此账号每月额度必须也有限制，请重新分配每月额度限制"));
                    }
                    //获取上级用户的所有子级
                    $son_customer = $this->db->select('id')->where(array('parent_id' => $post['parent_id']))->from('app_customer')->get()->result_array();

                    $parent_total_quota_used = 0;
                    foreach ($son_customer as $key => $value) {
                        $row = $this->db->select('total_quota')->where(array('customer_id' => $value['id']))->from('app_manager_user')->get()->row_array();
                        $parent_total_quota_used += $row['total_quota'];
                    }

                    //获取上级的每月额度和单品预算
                    $total_quota_left = $parent_info['total_quota'] - $parent_total_quota_used;
                    if (isset($post['total_quota']) && $post['total_quota'] > $total_quota_left) {
                        send_json(array('code' => -1, 'data' => '', 'msg' => "超出上级每月剩余额度(当前剩余" . $total_quota_left . "元)"));
                    }
                }
                if ($parent_info['single_quota'] != 0) {
                    if (!$post['single_quota']) {
                        send_json(array('code' => -1, 'data' => '', 'msg' => "由于上级账号单品额度有限制，所以此账号单品额度必须也有限制，请重新指定单品额度"));
                    }
                    if (isset($post['single_quota']) && $post['single_quota'] > $parent_info['single_quota']) {
                        send_json(array('code' => -1, 'data' => '', 'msg' => "超出上级单品预算"));
                    }
                }
            }

            $parent_shop_user_id = $this->user_model->customer_id_to_shop_user_id($post['parent_id']);

            $d1['identity'] = $post['identity'];
            $shop_info      = $this->customer_model->company_user_add(array('account' => $d1['username'], 'password' => $d1['password'], 'name' => $d1['name'], 'mobile' => $d1['tel'], 'email' => $d1['email'], "parent_id" => $parent_shop_user_id, 'type' => $admin_info['account_period_type'])); // 商城的接口获取
            if ($shop_info['code'] == 200) {
                $d1['shop_user_id'] = $shop_info['data']['shop_user_id'];
            } else {
                send_json(array('code' => -1, 'data' => '', 'msg' => $shop_info['msg']));
            }

            $d1['parent_id'] = $post['parent_id']; // 上级ID

            $r1 = $this->customer_model->save_customer_info($d1);

            if ($r1) {
                //创建用户的customer_id
                $manager_or_user_customer_id = $r1;
                //创建用户的商城id
                $shop_user_id = $this->user_model->customer_id_to_shop_user_id($manager_or_user_customer_id);
            } else {
                $this->db->trans_rollback();
                send_json(array('code' => -1, 'data' => '', 'msg' => "保存失败"));
            }
            // 身份信息 保存app_manager_user
            $d2['customer_id']         = $manager_or_user_customer_id;
            $d2['password']            = isset($post['password']) ? $post['password'] : '';
            $d2['total_quota']         = isset($post['total_quota']) ? $post['total_quota'] : 0;
            $d2['single_quota']        = isset($post['single_quota']) ? $post['single_quota'] : 0;
            $d2['activation']          = 0;
            $r2                        = $this->user_model->save_manager_user($d2);
            $budget_arr                = [];
            $budget_arr['customer_id'] = $manager_or_user_customer_id;
            $budget_arr['budget']      = $d2['total_quota'];
            $budget_arr['used']        = 0;
            $budget_arr['month']       = date("Y-m");
            $this->user_model->save_manager_user_budget($budget_arr);
            if ($r1 && $r2) {
                // 保存收获地址信息
                $address = [];
                if (isset($post['address_name'])) {
                    for ($i = 0; $i < count($post['address_name']); $i++) {
                        $address[$i]['name']      = $post['address_name'][$i];
                        $address[$i]['province']  = $post['address_province'][$i];
                        $address[$i]['city']      = $post['address_city'][$i];
                        $address[$i]['district']  = $post['address_district'][$i];
                        $address[$i]['address']   = $post['address_address'][$i];
                        $address[$i]['postcode']  = $post['address_code'][$i];
                        $address[$i]['phone']     = $post['address_telphone'][$i];
                        $address[$i]['tel']       = $post['address_phone'][$i];
                        $address[$i]['region_id'] = $post['region_id'][$i];
                        $data['shop_user_id']     = $d1['shop_user_id'];
                        $data['name']             = $post['address_name'][$i];
                        $data['region_id']        = $post['region_id'][$i];
                        $data['region_name']      = $post['address_province'][$i] . $post['address_city'][$i] . $post['address_district'][$i];
                        $data['address']          = $post['address_address'][$i];
                        $data['postcode']         = $post['address_code'][$i];
                        $data['tel']              = $post['address_phone'][$i];
                        $data['phone']            = $post['address_telphone'][$i];
                        $address[$i]['shop_id']   = $this->member_model->company_user_address($data);
                        if ($post['address_default'][$i] == 1) {
                            $this->member_model->company_user_address_default(array('shop_user_id' => $d1['shop_user_id'], 'shop_id' => $address[$i]['shop_id']));
                        }
                        $address[$i]['is_default']  = $post['address_default'][$i];
                        $address[$i]['customer_id'] = $manager_or_user_customer_id;
                    }
                    foreach ($address as $value) {
                        $this->user_model->add_address($value);
                    }
                }

                $invoice = [];
                if (isset($post['invoice_type'])) {
                    for ($i = 0; $i < count($post['invoice_type']); $i++) {
                        $invoice[$i]['invoice_type']         = $post['invoice_type'][$i];
                        $invoice[$i]['invoice_company_name'] = $post['invoice_company_name'][$i];
                        $invoice[$i]['invoice_code']         = $post['invoice_code'][$i];
                        $invoice[$i]['invoice_address']      = $post['invoice_address'][$i];
                        $invoice[$i]['invoice_tel']          = $post['invoice_tel'][$i];
                        $invoice[$i]['invoice_bank']         = $post['invoice_bank'][$i];
                        $invoice[$i]['invoice_content']      = "";
                        $invoice[$i]['invoice_account']      = $post['invoice_account'][$i];
                        $invoice[$i]['is_default']           = $post['invoice_default'][$i];
                        $invoice[$i]['customer_id']          = $manager_or_user_customer_id;
                        $invoice[$i]['shop_user_id']         = $shop_user_id;
                        $invoice[$i]['shop_id']              = $this->member_model->company_user_invoice($invoice[$i])['data'];
                    }
                    foreach ($invoice as $value) {
                        unset($value['shop_user_id']);
                        $this->db->insert('app_invoice', $value);
                    }
                }

                if (isset($post['list_ids'])) {
                    foreach ($post['list_ids'] as $value) {
                        $dataArr['list_id']           = $value;
                        $dataArr['customer_id']       = $manager_or_user_customer_id;
                        $dataArr['admin_customer_id'] = $this->customer_model->get_admin_customer_id($post['parent_id']);
                        $this->db->insert('app_customer_list', $dataArr);
                    }
                }

                $send['email']       = $post['email'];
                $send['title']       = '提示信息';
                $send['phone']       = $post['tel'];
                $send['username']    = $post['u_prefix'] . $post['username'];
                $send['password']    = $post['password'];
                $send['parent_info'] = $this->db->where(array('id' => $post['parent_id']))->from('app_customer')->get()->row_array();
                $send['parent_name'] = $send['parent_info']['username'];
                $send['content']     = '【文具1号】尊敬的客户，您好，您的管理员' . $send['parent_name'] . ',为您创建账号' . $send['username'] . ',密码' . $send['password'] . '.请登录www.wjyh.com，修改密码，进行采购哦。';
                $this->session->set_userdata('send', $send);

                // $res = $this->api_model->send_email_public($email, $title, $content);

                // $res = $this->message->send_msg($post['tel'], $msg);

                $this->db->trans_commit();
                send_json(array('code' => 0, 'data' => '', 'msg' => "success"));
            } else {
                $this->db->trans_rollback();
                send_json(array('code' => -1, 'data' => '', 'msg' => "保存失败"));
            }

        } else {
            send_json(array('code' => -1, 'data' => '', 'msg' => "缺少参数"));
        }
    }

    // 保存编辑管理/用户账号信息
    public function edit_manager_user()
    {
        $customer_id = $this->session->customer_id;
        $post        = $this->input->post();
        if (check_param($post, ['cost_center_id', 'password', 'name', 'tel', 'email', 'u_prefix', 'parent_id', 'customer_id'])) {
            $this->db->trans_begin();
            //被编辑用户customer_id
            $manager_or_user_customer_id = $post['customer_id'];

            $field = '*,
                        (select single_quota from app_manager_user where app_manager_user.customer_id = app_customer.id) as single_quota,
                        (select total_quota from app_manager_user where app_manager_user.customer_id = app_customer.id) as total_quota,
                        (select activation from app_manager_user where app_manager_user.customer_id = app_customer.id) as activation,
                        (select password from app_manager_user where app_manager_user.customer_id = app_customer.id) as password';
            $manager_or_user_info = $this->db->select($field)->where(array('id' => $manager_or_user_customer_id))->from('app_customer')->get()->row_array();
            // 基本信息 保存 app_customer
            $d1['cost_center_id'] = $post['cost_center_id'];
            if ($post['password'] == "") {
                $d1['password'] = $manager_or_user_info['password'];
            } else {
                if ($post['password'] == $manager_or_user_info['password']) {
                    send_json(array('code' => -1, 'data' => '', 'msg' => "新密码不能与原密码相同"));
                }
                $d1['password'] = $post['password'];
            }
            $d1['name']         = $post['name'];
            $d1['tel']          = $post['tel'];
            $d1['status']       = $manager_or_user_info['status'];
            $d1['manager_id']   = $manager_or_user_info['manager_id'];
            $d1['company']      = $manager_or_user_info['company'];
            $d1['identity']     = $manager_or_user_info['identity'];
            $d1['postage']      = $manager_or_user_info['postage'];
            $d1['discount']     = $manager_or_user_info['discount'];
            $d1['adjustments']  = $manager_or_user_info['adjustments'];
            $d1['shop_user_id'] = $manager_or_user_info['shop_user_id'];
            $d1['username']     = $manager_or_user_info['username'];
            $d1['created_at']   = $manager_or_user_info['created_at'];
            $d1['email']        = $post['email'];
            $this->db->where('id !=', $manager_or_user_info['id']);
            $this->db->where('tel =', $d1['tel']);
            $res = $this->db->from('app_customer')->get()->row_array();
            if ($res) {
                send_json(array('code' => -1, 'data' => '', 'msg' => "该手机号已被注册"));
            }

            $this->db->where('id !=', $manager_or_user_info['id']);
            $this->db->where('email =', $d1['email']);
            $res = $this->db->from('app_customer')->get()->row_array();
            if ($res) {
                send_json(array('code' => -1, 'data' => '', 'msg' => "该电子邮箱地址已存在"));
            }
            //获取上级id身份
            $admin_id = $this->user_model->customer_id_to_identity($post['parent_id']);

            if ($admin_id == 1) {
                //获取被编辑用户的所有子级
                $son_customer     = $this->db->select('id')->where(array('parent_id' => $manager_or_user_customer_id))->from('app_customer')->get()->result_array();
                $total_quota_used = 0;
                foreach ($son_customer as $key => $value) {
                    if ($value['id'] != $manager_or_user_customer_id) {

                        $row = $this->db->select('total_quota,single_quota')->where(array('customer_id' => $value['id']))->from('app_manager_user')->get()->row_array();
                        if ($post['single_quota'] < $row['single_quota']) {
                            send_json(array('code' => -1, 'data' => '', 'msg' => "由于该manager创建user分配的单品额度存在超出您现在设置的单品额度，请先修改该用户创建的user单品额度"));
                        }
                        $total_quota_used += $row['total_quota'];
                    }
                }
                if (isset($post['total_quota']) && $post['total_quota'] < $total_quota_used) {
                    send_json(array('code' => -1, 'data' => '', 'msg' => "由于该manager创建user分配的每月额度总和超出您现在设置的每月额度，请先修改该用户创建的user每月额度"));
                }
            }
            if ($admin_id == 2) {
                //获取上级所有信息
                $parent_info = $this->db->where(array('customer_id' => $post['parent_id']))->from('app_manager_user')->get()->row_array();
                if ($parent_info['total_quota'] != 0) {
                    if (!$post['total_quota']) {
                        send_json(array('code' => -1, 'data' => '', 'msg' => "由于上级账号每月额度有限制，所以此账号每月额度必须也有限制，请重新分配每月额度限制"));
                    }

                    //获取上级用户的所有子级
                    $son_customer            = $this->db->select('id')->where(array('parent_id' => $post['parent_id']))->from('app_customer')->get()->result_array();
                    $parent_total_quota_used = 0;
                    foreach ($son_customer as $key => $value) {
                        if ($value['id'] != $manager_or_user_customer_id) {
                            $row = $this->db->select('total_quota')->where(array('customer_id' => $value['id']))->from('app_manager_user')->get()->row_array();
                            $parent_total_quota_used += $row['total_quota'];
                        }

                    }
                    //获取上级的每月额度和单品预算
                    $total_quota_left = $parent_info['total_quota'] - $parent_total_quota_used;
                    if (isset($post['total_quota']) && $post['total_quota'] > $total_quota_left) {
                        send_json(array('code' => -1, 'data' => '', 'msg' => "超出上级每月剩余额度(当前剩余" . $total_quota_left . "元)"));
                    }
                }
                if ($parent_info['single_quota'] != 0) {
                    if (!$post['single_quota']) {
                        send_json(array('code' => -1, 'data' => '', 'msg' => "由于上级账号单品额度有限制，所以此账号单品额度必须也有限制，请重新指定单品额度"));
                    }
                    if (isset($post['single_quota']) && $post['single_quota'] > $parent_info['single_quota']) {
                        send_json(array('code' => -1, 'data' => '', 'msg' => "超出上级单品预算"));
                    }
                }
            }

            $this->member_model->company_user_edit(array('password' => $d1['password'], 'name' => $d1['name'], 'tel' => $d1['tel'], 'email' => $d1['email'], 'shop_user_id' => $d1['shop_user_id'])); // 商城的接口获取

            $d1['parent_id'] = $post['parent_id']; // 上级ID

            $r1 = $this->customer_model->save_customer_info($d1, $manager_or_user_customer_id);
            if (!$r1) {
                $this->db->trans_rollback();
                send_json(array('code' => -1, 'data' => '', 'msg' => "保存失败"));
            }
            if ($r1 && $admin_id == 1) {
                //获取被编辑用户的所有子级
                $son_customer = $this->db->select('id')->where(array('parent_id' => $manager_or_user_customer_id))->from('app_customer')->get()->result_array();
                if ($son_customer) {
                    foreach ($son_customer as $k => $v) {
                        $where = array('id' => $v['id']);
                        $this->db->where($where)->update('app_customer', array('cost_center_id' => $d1['cost_center_id']));
                    }
                }
            }
            // 身份信息 保存app_manager_user
            $d2['customer_id']         = $manager_or_user_customer_id;
            $d2['password']            = $d1['password'];
            $d2['total_quota']         = isset($post['total_quota']) ? $post['total_quota'] : '';
            $d2['single_quota']        = isset($post['single_quota']) ? $post['single_quota'] : '';
            $d2['activation']          = $manager_or_user_info['activation'];
            $r2                        = $this->user_model->save_manager_user($d2, $manager_or_user_customer_id);
            $budget_arr                = [];
            $budget_arr['customer_id'] = $manager_or_user_customer_id;
            $budget_arr['budget']      = $d2['total_quota'];
            $budget_arr['used']        = 0;
            $budget_arr['month']       = date("Y-m");
            $this->user_model->save_manager_user_budget($budget_arr, $manager_or_user_customer_id, date("Y-m"));

            if ($r1 && $r2) {
                //记录修改的值
                $customer_record                         = [];
                $customer_record['customer_id']          = $manager_or_user_customer_id;
                $customer_record['operator_customer_id'] = $customer_id;
                $customer_record['created_at']           = date("Y-m-d H:i:s", time());
                if ($manager_or_user_info['cost_center_id'] != $post['cost_center_id']) {
                    $customer_record['update_text'] = "修改成本中心";
                    $customer_record['new_value']   = $post['cost_center_id'];
                    $this->db->insert('app_customer_record', $customer_record);
                }
                if ($manager_or_user_info['name'] != $post['name']) {
                    $customer_record['update_text'] = "修改联系人";
                    $customer_record['new_value']   = $post['name'];
                    $this->db->insert('app_customer_record', $customer_record);
                }
                if ($manager_or_user_info['tel'] != $post['tel']) {
                    $customer_record['update_text'] = "修改联系方式";
                    $customer_record['new_value']   = $post['tel'];
                    $this->db->insert('app_customer_record', $customer_record);
                }
                if ($manager_or_user_info['email'] != $post['email']) {
                    $customer_record['update_text'] = "修改电子邮箱";
                    $customer_record['new_value']   = $post['email'];
                    $this->db->insert('app_customer_record', $customer_record);
                }
                if ($post['password'] && ($manager_or_user_info['password'] != $post['password'])) {
                    $customer_record['update_text'] = "修改密码";
                    $customer_record['new_value']   = $post['password'];
                    $this->db->insert('app_customer_record', $customer_record);
                }
                if ($manager_or_user_info['total_quota'] != $post['total_quota']) {
                    $customer_record['update_text'] = "修改每月额度";
                    $customer_record['new_value']   = $post['total_quota'];
                    $this->db->insert('app_customer_record', $customer_record);

                    $message_history['receiver_customer_id'] = $manager_or_user_customer_id;
                    $message_history['send_customer_id']     = $post['parent_id'];
                    $message_history['title']                = '月预算额度调整';
                    $message_history['content']              = '尊敬的客户，您的月预算额度已调整为' . $post['total_quota'] . '元！';
                    $message_history['read_status']          = 0;
                    $message_history['created_at']           = date("Y-m-d H:i:s", time());
                    $result                                  = $this->db->insert('message_history', $message_history);
                }
                if ($manager_or_user_info['single_quota'] != $post['single_quota']) {
                    $customer_record['update_text'] = "修改单品额度";
                    $customer_record['new_value']   = $post['single_quota'];
                    $this->db->insert('app_customer_record', $customer_record);

                    $message_history['receiver_customer_id'] = $manager_or_user_customer_id;
                    $message_history['send_customer_id']     = $post['parent_id'];
                    $message_history['title']                = '单品额度调整';
                    $message_history['content']              = '尊敬的客户，您的单品额度已调整为' . $post['single_quota'] . '元！';
                    $message_history['read_status']          = 0;
                    $message_history['created_at']           = date("Y-m-d H:i:s", time());
                    $result                                  = $this->db->insert('message_history', $message_history);
                }
                if (isset($post['list_ids'])) {
                    $where = array('customer_id' => $manager_or_user_customer_id);
                    $this->db->where($where)->delete('app_customer_list');
                    foreach ($post['list_ids'] as $value) {
                        $dataArr['list_id']           = $value;
                        $dataArr['customer_id']       = $manager_or_user_customer_id;
                        $dataArr['admin_customer_id'] = $this->customer_model->get_admin_customer_id($post['parent_id']);
                        $this->db->insert('app_customer_list', $dataArr);
                    }
                } else {
                    $where = array('customer_id' => $manager_or_user_customer_id);
                    $this->db->where($where)->delete('app_customer_list');
                }

                $send['email']    = $post['email'];
                $send['title']    = '提示信息';
                $send['phone']    = $post['tel'];
                $send['username'] = $manager_or_user_info['username'];

                $send['content'] = '【文具1号】尊敬的客户，您的账户' . $send['username'] . '信息已更改，请登录文具1号（www.wjyh.com）查看！';
                $this->session->set_userdata('send', $send);

                $this->db->trans_commit();
                send_json(array('code' => 0, 'data' => '', 'msg' => "success"));
            } else {
                $this->db->trans_rollback();
                send_json(array('code' => -1, 'data' => '', 'msg' => "保存失败"));
            }

        } else {
            send_json(array('code' => -1, 'data' => '', 'msg' => "缺少参数"));
        }
    }

    public function send_email_phone()
    {
        $send = $this->session->send;
        $post = $this->input->post();
        if ($post['type'] == 1) {
            $res = $this->api_model->send_email_public($send['email'], $send['title'], $send['content']);
        } else {
            $res = $this->message->send_msg($send['phone'], $send['content']);
        }
        if ($res) {
            send_json(array('code' => 0, 'data' => '', 'msg' => "success"));
        } else {
            send_json(array('code' => -1, 'data' => '', 'msg' => "保存成功，邮件发送失败"));
        }
    }

    // 创建管理账号
    public function create_manager_index()
    {
        $customer_info = $this->session->customer_info;
        if ($customer_info['identity'] != 1) {
            redirect('cost_center/no_permission_index');
        }
        $data['customer_info'] = $customer_info;
        $customer_id           = $this->session->customer_id;
        $data['customer_id']   = $customer_id;

        $data['cost_center_list']     = $this->cost_center_model->query_cost_center_list($customer_id);
        $data['admin_info']           = $this->admin_model->query_admin_info($customer_id);
        $data['manager_address_list'] = $this->user_model->query_user_address_list($customer_id);
        $data['manager_invoice_list'] = $this->user_model->query_user_invoice_list($customer_id);

        // 是否创建过 manager 或 user
        $sql = "select count(1) as res from app_customer WHERE parent_id = " . $customer_id;
        $res = $this->db->query($sql)->row_array()['res'];
        if ($res) {
            $data['prefix'] = false;
        } else {
            $data['prefix'] = true;
        }

        $data_arr['time'] = time();
        $data_arr['key']  = md5($this->config->item("token_const_wjyh") . $data_arr['time']);
        $uid              = $this->user_model->customer_id_to_shop_user_id($customer_id);
        $url              = $this->config->item("shop_url") . '/companymanagerapi/mPur_mylist/?time=' . $data_arr['time'] . '&key=' . $data_arr['key'] . '&uid=' . $uid;
        $rs               = curl_request($url);
        $data1            = json_decode($rs, true);
        $data['center']   = $data1['data'];
        $costlist         = $this->db->select('c.list_id')->where('c.customer_id', $customer_id)->from('app_customer_list c')->get();
        $costlist         = $costlist->result_array();
        $list             = array();
        foreach ($costlist as $key2 => $lis) {
            $list[$lis['list_id']] = $lis['list_id'];
        }
        $centertotal = array();
        $center      = array();
        $amount      = array();
        foreach ($data['center'] as $key => $sum) {
            if (in_array($sum['id'], $list)) {
                $center[$key]                   = $sum;
                $centertotal[$sum['total_num']] = $sum['total_num'];
                $amount[$sum['amount']]         = $sum['amount'];
            }
        }
        //发票抬头
        $where           = array('customer_id' => $customer_id);
        $data['invoice'] = $this->db->where($where)->from('app_invoice')->order_by('id', 'desc')->get()->result_array();

        $data['centertotal'] = $centertotal;
        $data['costlist']    = $list;
        $data['centerlist']  = $center;
        $data['customer_id'] = $customer_id;
        $data['amount']      = array_sum($amount);
        $data['is_account']  = $this->db->where(array('customer_id' => $customer_id))->from('app_admin')->get()->row_array()['is_account'];
        $this->load->view('cost_center/create_manager_index.php', $data);

    }

    // 创建用户user账号
    public function create_user_index()
    {
        $customer_info = $this->session->customer_info;
        $customer_id   = $this->session->customer_id;
        if ($customer_info['identity'] == 3) {
            redirect('cost_center/no_permission_index');
        }
        $data_arr['time'] = time();
        $data_arr['key']  = md5($this->config->item("token_const_wjyh") . $data_arr['time']);
        //获取登录用户的admin_id
        $user_admin_id = $this->customer_model->get_admin_customer_id($customer_id);

        $uid = $this->user_model->customer_id_to_shop_user_id($user_admin_id);

        $url  = $this->config->item("shop_url") . '/companymanagerapi/mPur_mylist/?time=' . $data_arr['time'] . '&key=' . $data_arr['key'] . '&uid=' . $uid;
        $rs   = curl_request($url);
        $data = json_decode($rs, true);

        $data['customer_info']    = $this->customer_model->query_customer_info($customer_id);
        $data['customer_id']      = $customer_id;
        $data['cost_center_list'] = $this->cost_center_model->query_cost_center_list($customer_id);
        $data['manager_list']     = $this->customer_model->query_manager_list($customer_id);
        if ($customer_info['identity'] == 1) {
            $data['admin_info'] = $this->admin_model->query_admin_info($customer_id);
        } else {
            //获取admin的id
            $admin_id           = $this->customer_model->get_admin_customer_id($customer_id);
            $data['admin_info'] = $this->admin_model->query_admin_info($admin_id);
        }

        $data['manager_address_list'] = $this->user_model->query_user_address_list($customer_id);
        $data['manager_invoice_list'] = $this->user_model->query_user_invoice_list($customer_id);

        $data['center'] = $data['data'];

        //如果用户identity为2 获取用户的清单
        if ($customer_info['identity'] == 2) {
            $user_costlist = [];
            $user_costlist = $this->db->select('c.list_id')->where('c.customer_id', $customer_id)->from('app_customer_list c')->get();
            $user_costlist = $user_costlist->result_array();
            $user_list     = array();
            foreach ($user_costlist as $key => $value) {
                $user_list[$value['list_id']] = $value['list_id'];
            }

            $user_centertotal = array();
            $user_center      = array();
            $user_amount      = array();

            foreach ($data['center'] as $key => $sum) {
                if (in_array($sum['id'], $user_list)) {
                    $user_center[$key]                   = $sum;
                    $user_centertotal[$sum['total_num']] = $sum['total_num'];
                    $user_amount[$sum['amount']]         = $sum['amount'];
                }
            }

            $data['user_centertotal'] = $user_centertotal;
            $data['user_costlist']    = $user_list;
            $data['user_centerlist']  = $user_center;
            $data['user_amount']      = array_sum($user_amount);
        } else {
            $data['user_centertotal'] = "";
            $data['user_list']        = "";
            $data['user_centerlist']  = "";
            $data['user_amount']      = "";
        }
        $data['is_account'] = $this->db->where(array('customer_id' => $user_admin_id))->from('app_admin')->get()->row_array()['is_account'];
        $this->load->view('cost_center/create_user_index.php', $data);

    }

    //修改创建的user或manager（必须是该manager或user的上级或者上上级才可以修改）
    public function manager_user_edit()
    {
        $customer_info = $this->session->customer_info;
        $customer_id   = $this->session->customer_id;

        if ($customer_info['identity'] == 3) {
            redirect('cost_center/no_permission_index');
        }
        if (isset($_GET['id'])) {
            $id = $_GET['id'];
        } else {
            $id = "";
        }

        if (!$id) {
            exit('用户不存在');
        }
        $where = array(
            'id' => $id,
        );

        $data_arr['time'] = time();
        $data_arr['key']  = md5($this->config->item("token_const_wjyh") . $data_arr['time']);
        //获取登录用户的admin_id
        $user_admin_id = $this->customer_model->get_admin_customer_id($customer_id);

        $uid = $this->user_model->customer_id_to_shop_user_id($user_admin_id);

        //获取用户admin的所有清单
        $url  = $this->config->item("shop_url") . '/companymanagerapi/mPur_mylist/?time=' . $data_arr['time'] . '&key=' . $data_arr['key'] . '&uid=' . $uid;
        $rs   = curl_request($url);
        $data = json_decode($rs, true);

        $data['user_id']   = $id;
        $data['user_info'] = $this->db->where($where)->from('app_customer')->get()->row_array();
        if (!$data['user_info']) {
            exit('用户不存在');
        }
        //判断是否为自己所创建的user或者manager
        if ($customer_info['identity'] == 3) {
            exit('非法操作');
        } elseif ($customer_info['identity'] == 2) {
            //获取用户的子级
            $son_info = $this->db->select('id')->where(array('parent_id' => $customer_id))->from('app_customer')->get()->result_array();
            $son_id   = [];
            foreach ($son_info as $key => $value) {
                $son_id[$key] = $value['id'];
            }
            if (!in_array($data['user_id'], $son_id)) {
                exit('非法操作');
            }
        } else {
            //获取用户的子级
            $son_info = $this->customer_model->get_customer_user($customer_id, 1);
            if (!in_array($data['user_id'], $son_info)) {
                exit('非法操作');
            }
        }

        $where = array(
            'customer_id' => $id,
        );
        $data['user_quota']       = $this->db->where($where)->from('app_manager_user')->get()->row_array();
        $data['user_list']        = $this->db->where($where)->from('app_customer_list')->get()->result_array();
        $data['user_address']     = $this->db->where($where)->from('app_address')->get()->result_array();
        $data['user_invoice']     = $this->db->where($where)->from('app_invoice')->get()->result_array();
        $data['customer_info']    = $this->customer_model->query_customer_info($customer_id);
        $data['customer_id']      = $customer_id;
        $data['cost_center_list'] = $this->cost_center_model->query_cost_center_list($customer_id);
        $data['manager_list']     = $this->customer_model->query_manager_list($customer_id);
        if ($customer_info['identity'] == 1) {
            $data['admin_info'] = $this->admin_model->query_admin_info($customer_id);
        } else {
            //获取admin的id
            $admin_id           = $this->customer_model->get_admin_customer_id($customer_id);
            $data['admin_info'] = $this->admin_model->query_admin_info($admin_id);
        }

        $data['manager_address_list'] = $this->user_model->query_user_address_list($data['user_info']['id']);
        $data['manager_invoice_list'] = $this->user_model->query_user_invoice_list($data['user_info']['id']);

        $data['center'] = $data['data'];

        //如果用户identity为2 获取用户的清单
        if ($customer_info['identity'] == 2) {
            $user_costlist = [];
            $user_costlist = $this->db->select('c.list_id')->where('c.customer_id', $customer_id)->from('app_customer_list c')->get();
            $user_costlist = $user_costlist->result_array();
            $user_list     = array();
            foreach ($user_costlist as $key => $value) {
                $user_list[$value['list_id']] = $value['list_id'];
            }

            $user_centertotal = array();
            $user_center      = array();
            $user_amount      = array();

            foreach ($data['center'] as $key => $sum) {
                if (in_array($sum['id'], $user_list)) {
                    $user_center[$key]                   = $sum;
                    $user_centertotal[$sum['total_num']] = $sum['total_num'];
                    $user_amount[$sum['amount']]         = $sum['amount'];
                }
            }

            $data['user_centertotal'] = $user_centertotal;
            $data['user_costlist']    = $user_list;
            $data['user_centerlist']  = $user_center;
            $data['user_amount']      = array_sum($user_amount);
        } else {
            $data['user_centertotal'] = "";
            $data['user_list']        = "";
            $data['user_centerlist']  = "";
            $data['user_amount']      = "";
        }

        //获取编辑用户的清单
        $edit_costlist = $this->db->select('c.list_id')->where('c.customer_id', $data['user_info']['id'])->from('app_customer_list c')->get();

        $edit_costlist = $edit_costlist->result_array();

        $edit_list = array();
        foreach ($edit_costlist as $key2 => $lis) {
            $edit_list[$lis['list_id']] = $lis['list_id'];
        }

        $edit_centertotal = array();
        $edit_center      = array();
        $edit_amount      = array();

        foreach ($data['center'] as $key => $sum) {
            if (in_array($sum['id'], $edit_list)) {
                $edit_center[$key]  = $sum;
                $edit_centertotal[] = $sum['total_num'];
                $edit_amount[]      = $sum['amount'];
            }

        }
        $data['edit_centertotal'] = $edit_centertotal;
        $data['edit_costlist']    = $edit_list;
        $data['edit_centerlist']  = $edit_center;
        $data['edit_amount']      = array_sum($edit_amount);
        $data['is_account']       = $this->db->where(array('customer_id' => $user_admin_id))->from('app_admin')->get()->row_array()['is_account'];
        $this->load->view('cost_center/manager_user_edit.php', $data);
    }

    // 无权查看页面
    public function no_permission_index()
    {
        $this->load->view('cost_center/no_permission_index.php');
    }

//成本中心介绍
    public function cost_center_present()
    {
        $this->load->view('cost_center/cost_center_present');
    }

//多地址下单介绍
    public function cost_center_address_present()
    {
        $this->load->view('cost_center/cost_center_address_present');
    }

//管理账户介绍
    public function cost_center_manage_present()
    {
        $this->load->view('cost_center/cost_center_manage_present');
    }

    //用户账户介绍
    public function cost_center_user_present()
    {
        $this->load->view('cost_center/cost_center_user_present');
    }

//    public function query_list()
    //    {
    //        $customer_id = $this->session->customer_id;
    //        $user_admin_id = $this->customer_model->get_admin_customer_id($customer_id);
    //        $uid = $this->user_model->customer_id_to_shop_user_id($user_admin_id);
    //
    //        $shop_user_id = $uid;
    //        $list_id = $_GET['list_id'];
    //        if (rtrim($list_id, ',')) {
    //            $lists = $this->customer_model->query_customer_list_cost_center($shop_user_id, rtrim($list_id, ','));
    //            if (!empty($lists)) {
    //                if ($lists['code'] == 200) {
    //                    $data['goods'] = $lists['data'];
    //                    $data['goodstotal'] = count($lists['data']);
    //                } else {
    //                    $data['goods'] = array();
    //                    $data['goodstotal'] = 0;
    //                }
    //            } else {
    //                $data['goods'] = array();
    //                $data['goodstotal'] = 0;
    //            }
    //        } else {
    //            $data['goods'] = array();
    //            $data['goodstotal'] = 0;
    //        }
    //        send_json(array('code' => 1, 'data' => $data, 'msg' => ""));
    //    }
}
